﻿@page "/_School/School/Edit/{id}"
@using WBBvNext.ViewModel._School.SchoolVMs;
@inherits BasePage

<ValidateForm @ref="vform" Model="@Model" OnValidSubmit="@Submit">
    <Row ItemsPerRow="ItemsPerRow.Two" RowType="RowType.FormRow">

            <BootstrapInput @bind-Value="@Model.Entity.SchoolCode"  />
            <BootstrapInput @bind-Value="@Model.Entity.SchoolName"  />
            <Select @bind-Value="@Model.Entity.SchoolType"  PlaceHolder="@WtmBlazor.Localizer["Sys.PleaseSelect"]"/>
            <WTUploadFile @bind-Value="@Model.Entity.PdfFileId" CSKey="School" OnBeforeDelete="OnPdfBeforeDelete" Accept="application/pdf"  />
            <BootstrapInput @bind-Value="@Model.Entity.Remark"  />
    </Row>
    <div class="modal-footer table-modal-footer">
        <Button Color="Color.Primary" Icon="fa fa-save" Text="@WtmBlazor.Localizer["Sys.Close"]" OnClick="OnClose" />
        <Button Color="Color.Primary" ButtonType="ButtonType.Submit" Icon="fa fa-save" Text="@WtmBlazor.Localizer["Sys.Edit"]" IsAsync="true" />
    </div>
</ValidateForm>

@code {

    private SchoolVM Model = null;
    private ValidateForm vform { get; set; }
    [Parameter]
    public string id { get; set; }


    protected override async Task OnInitializedAsync()
    {

        var rv = await WtmBlazor.Api.CallAPI<SchoolVM>($"/api/School/{id}");
        Model = rv.Data;
        await base.OnInitializedAsync();
    }

    private async Task<bool> OnPdfBeforeDelete(string id)
    {
        var dc = WtmBlazor.ConfigInfo.CreateDC("School");
        var school = dc.Set<WBBvNext.School.Model.School>().FirstOrDefault(m => m.ID == Model.Entity.ID);
        school.PdfFileId = null;
        var result = await dc.SaveChangesAsync();
        return result > 0;
    }

    private async Task Submit(EditContext context)
    {
        await PostsForm(vform, $"/api/School/edit", (s) => "Sys.OprationSuccess", method: HttpMethodEnum.PUT);
    }

    public void OnClose()
    {
        CloseDialog();
    }

}
